package com.banmao.dynamicDS.datasource;

import lombok.extern.slf4j.Slf4j;

import java.util.Stack;

@Slf4j
public class DatasourceContextHolder {

    private static final ThreadLocal<Stack<String>> CONTEXT_HOLDER = new ThreadLocal<>();

    public static String defaultdatasource;

    public static void setDS(String dsType) {
        log.info("切换数据源:{}", dsType);
        Stack<String> stack = CONTEXT_HOLDER.get();
        if (stack == null) {
            CONTEXT_HOLDER.set(new Stack<>());
            stack = CONTEXT_HOLDER.get();
        }

        stack.push(dsType);
        CONTEXT_HOLDER.set(stack);
    }

    public static String getDS() {
        if (CONTEXT_HOLDER.get() == null) {
            return defaultdatasource;
        }
        return CONTEXT_HOLDER.get().peek();
    }

    public static void clearDS() {
        CONTEXT_HOLDER.remove();
    }

    public static void popDS() {
        if (CONTEXT_HOLDER.get() == null) {
            return;
        }
        CONTEXT_HOLDER.get().pop();
    }

    public static void setDefaultdatasource(String defaultdatasource) {
        DatasourceContextHolder.defaultdatasource = defaultdatasource;
    }

    public static String getDefaultdatasource() {
        return defaultdatasource;
    }



}
